package com.wsz.security_fx.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wsz.security_fx.pojo.Role;
import com.wsz.security_fx.pojo.User;
import com.wsz.security_fx.pojo.UserRole;
import com.wsz.security_fx.service.RoleService;
import com.wsz.security_fx.service.UserRoleService;
import com.wsz.security_fx.service.UserService;
import com.wsz.security_fx.utils.RedisOperator;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class UserDetailsServerImpl implements UserDetailsService {

    private final RedisOperator redisOperator;

    private final UserService userService;

    private final UserRoleService userRoleService;

    private final RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<UserRole> urids = userRoleService.list(new QueryWrapper<UserRole>().eq("uid", user.getId()).select("rid"));
        List<Integer> rids = urids.stream().map(UserRole::getRid).collect(Collectors.toList());

        List<Role> roles = roleService.list(new QueryWrapper<Role>().in("id", rids));

        user.setRoles(roles);

        redisOperator.set("user:"+user.getUsername(),user,2 * 60);

        return user;
    }
}
